package com.sec.android.app.myfiles.module.shortcut;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.res.Configuration;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.View;

import com.sec.android.app.myfiles.fragment.filelist.FileListFragment;
import com.sec.android.app.myfiles.fragment.filelist.PathIndicator;
import com.sec.android.app.myfiles.info.AppFeatures;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.module.local.foldertree.FolderTreeDbTableInfo;
import com.sec.android.app.myfiles.navigation.NavigationInfo;
import com.sec.android.app.myfiles.navigation.NavigationManager;
import com.sec.android.app.myfiles.provider.DbTableInfo;
import com.sec.android.app.myfiles.util.UiUtils;
import com.sec.android.app.myfiles.widget.listview.EditOrderList;

import java.util.ArrayList;

public class ManageShortcutListFragment extends FileListFragment implements EditOrderList.OnMoveCompletedListener {
    private static final String TAG = "ManageShortcutListFragment";
    private ArrayList<ContentValues> mShortcutItems;
    private boolean isDensityDpiChanged = false;

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mShortcutItems = new ArrayList<>();

        EditOrderList editOrderList = (EditOrderList) mListViewImp.getListView();
        if (editOrderList != null) {
            editOrderList.setOnMoveCompletedListener(this);
        }
//        SamsungAnalyticsLog.setScreenInfo(SamsungAnalyticsLog.ScreenPath.MANAGE_SHORTCUT);   //TODO : HJ SA
    }

    @Override
    protected void setMouseKeyboardListener() {
        // nothing
    }

    @Override
    public void onOrderChanged(int source, int destination) {
        Log.i(TAG, "onOrderChanged");

        DbTableInfo tableInfo = DbTableInfo.getInstance(FileRecord.StorageType.Shortcut);
        StringBuilder selection = new StringBuilder();
        selection.append(tableInfo.getColumnName(DbTableInfo.COLUMN_ID.SHORTCUT_TYPE)).append('=')
                .append(FileRecord.ShortcutType.MyFiles.ordinal());

        getShortcutDBData(tableInfo, selection);

        ContentValues srcShortcutInfo = mShortcutItems.get(source);
        mShortcutItems.remove(source);
        mShortcutItems.add(destination, srcShortcutInfo);

        int count = mShortcutItems.size();
        changeShortcutDBData(tableInfo, selection, count);

        mShortcutItems.clear();
        if (AppFeatures.isTabletUIMode()) {
            DbTableInfo FolderTreeTableInfo = FolderTreeDbTableInfo.getInstance();
            mContext.getContentResolver().notifyChange(Uri.parse(FolderTreeTableInfo.getUri()), null);
        }
    }

    private void getShortcutDBData(DbTableInfo tableInfo, StringBuilder selection) {
        ContentResolver cr = mContext.getContentResolver();
        Uri uri = Uri.parse(tableInfo.getUri());

        try (Cursor cursor = cr.query(uri, null, selection.toString(), null, null)) {
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    do {
                        int shortcutType = cursor.getInt(cursor.getColumnIndex(tableInfo.getColumnName(DbTableInfo.COLUMN_ID.SHORTCUT_TYPE)));
                        String path = cursor.getString(cursor.getColumnIndex(tableInfo.getColumnName(DbTableInfo.COLUMN_ID.PATH)));
                        String name = cursor.getString(cursor.getColumnIndex(tableInfo.getColumnName(DbTableInfo.COLUMN_ID.NAME)));
                        String mimeType = cursor.getString(cursor.getColumnIndex(tableInfo.getColumnName(DbTableInfo.COLUMN_ID.MIME_TYPE)));
                        int fileType = cursor.getInt(cursor.getColumnIndex(tableInfo.getColumnName(DbTableInfo.COLUMN_ID.FILE_TYPE)));

                        ContentValues shortcutInfo = new ContentValues();
                        shortcutInfo.put(tableInfo.getColumnName(DbTableInfo.COLUMN_ID.SHORTCUT_TYPE), shortcutType);
                        shortcutInfo.put(tableInfo.getColumnName(DbTableInfo.COLUMN_ID.PATH), path);
                        shortcutInfo.put(tableInfo.getColumnName(DbTableInfo.COLUMN_ID.NAME), name);
                        shortcutInfo.put(tableInfo.getColumnName(DbTableInfo.COLUMN_ID.MIME_TYPE), mimeType);
                        shortcutInfo.put(tableInfo.getColumnName(DbTableInfo.COLUMN_ID.FILE_TYPE), fileType);
                        mShortcutItems.add(shortcutInfo);
                    } while (cursor.moveToNext());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void changeShortcutDBData(DbTableInfo tableInfo, StringBuilder selection, int count) {
        mContext.getContentResolver().delete(Uri.parse(tableInfo.getUri()), selection.toString(), null);

        for (int i = 0; i < count; i++) {
            mContext.getContentResolver().insert(Uri.parse(tableInfo.getUri()), mShortcutItems.get(i));
        }
    }

    @Override
    public void setPathIndicator(PathIndicator pathIndicator) {
        if (pathIndicator != null && mNavigationInfo != null) {
            pathIndicator.setFragment(this);
            if (AppFeatures.isTabletUIMode()) {
                super.setPathIndicator(pathIndicator);
            } else {
                pathIndicator.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void finishActionMode() {
        NavigationManager navigationManager = NavigationManager.getInstance(getProcessId());
        NavigationInfo info = navigationManager.getCurInfo();
        if (info != null && info.getStorageType() == FileRecord.StorageType.Shortcut) {
            if (mListViewImp != null && mListViewImp.getCount() != 0 && !isDensityDpiChanged) {
                updateActionBarMenu();
                mListViewImp.clearChoices();
                return;
            }
        }
        super.finishActionMode();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        isDensityDpiChanged = true;
        super.onConfigurationChanged(newConfig);
        isDensityDpiChanged = false;
    }

    @Override
    public void onDestroyActionMode(ActionMode mode) {
        Log.a(this, "onDestroyActionMode()");
        NavigationManager navigationManager = NavigationManager.getInstance(getProcessId());
        NavigationInfo info = navigationManager.getCurInfo();
        if (info != null && info.getStorageType() == FileRecord.StorageType.Shortcut) {
            if (mActivity != null && !UiUtils.isDensityDpiChanged(getContext().getResources().getConfiguration(), mActivity.getDensityDpi())) {
                navigationManager.leave(mContext);
            }
        }
    }
}
